package com.company.server;

import com.company.common.Message;
import com.company.common.User;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.time.LocalDateTime;

public class IMServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(8080);) {
            System.out.println("服务端在" + serverSocket.getLocalPort() + "端口监听...");
            new Thread(new MessagePushThd()).start();
            while (true) {
                Socket socket = serverSocket.accept();
                ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
                Message message = (Message) inputStream.readObject();
                switch (message.getType()) {
                    case REGISTER:
                        User user = (User) message.getContent();
                        Message<String> obj = new Message<String>("", Message.MessageType.REGISTER_FAIL, user.getName(), "", LocalDateTime.now());
                        if (UserDao.register(user)) {
                            obj.setType(Message.MessageType.REGISTER_SUCCEED);
                        }
                        outputStream.writeObject(obj);
                        inputStream.close();
                        outputStream.close();
                        socket.close();
                        break;
                    case LOGIN:
                        user = (User) message.getContent();
                        obj = new Message<String>("", Message.MessageType.LOGIN_FAIL, user.getName(), "", LocalDateTime.now());
                        if (UserDao.login(user)) {
                            obj.setType(Message.MessageType.LOGIN_SUCCEED);
                            outputStream.writeObject(obj);
                            ConnCliThread thread = new ConnCliThread(socket);
                            ConnCliThdManage.add(user.getName(), thread);
                            thread.start();
                            System.out.println("服务端和客户端" + user.getName() + "保持通信..." + " 时间：" + LocalDateTime.now());
                        } else {
                            outputStream.writeObject(obj);

                            inputStream.close();
                            outputStream.close();
                            socket.close();
                        }
                        break;
                    default:
                        throw new IllegalStateException("Unexpected value: " + message.getType());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
